package me.hys.base;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.hys.entity.system.UserEntity;
import me.hys.kits.StrKit;
import me.hys.service.system.IModuleManager;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.common.collect.Maps;

public class BaseAction {
	/**
	 * @Fields : 用户保存于session的key
	 */
	public static final String USER = "user";
	@Autowired
	protected HttpServletRequest request;
	@Autowired
	protected HttpServletResponse response;

	@Autowired
	private IModuleManager moduleManager;
	private String flag;

	protected Map<String, Object> getMap() {
		Map<String, Object> map = Maps.newHashMap();
		map.put("modules", moduleManager.findAll());
		map.put("current", moduleManager.findCurrent(flag));
		return map;
	}

	/**
	 * @Title : getPageQuery
	 * @Description : 获取分页参数
	 */
	protected <T> PageQuery<T> getPageQuery() {
		PageQuery<T> pageQuery = new PageQuery<T>();
		String start = request.getParameter("start");
		if (StrKit.isBlank(start)) {
			start = "1";
		}
		pageQuery.setStart(Integer.parseInt(start));
		pageQuery.getCondition().put("start",
				(pageQuery.getStart() - 1) * pageQuery.getLimit());
		pageQuery.getCondition().put("limit", pageQuery.getLimit());
		return pageQuery;
	}

	protected String getSuccessUrl(String url) {
		if (!StrKit.contains(url, "?s=true")) {
			url += "?s=true";
		}
		return url;
	}

	/**
	 * @Title : getUser
	 * @Description : 获取当前的登录用户
	 */
	protected UserEntity getUser() {
		Subject subject = SecurityUtils.getSubject();
		return (UserEntity) subject.getSession().getAttribute(BaseAction.USER);
	}

	/**
	 * @Title : setFlag
	 * @Description : 设置当前模块标志
	 */
	protected void setFlag(String flag) {
		this.flag = flag;
	}
}
